package com.example.servlet.manager;

import com.example.entity.Manager;
import com.example.service.ManagerService;
import com.example.service.impl.ManagerServiceImpl;
import com.example.utils.MybatisUtil;
import com.example.utils.ThymeleafUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.context.Context;

import java.io.IOException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

@WebServlet("/manager_order")
public class mOrderServlet extends HttpServlet {
    private ManagerService service;
    private SqlSession sqlSession;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new ManagerServiceImpl(sqlSession);
    }

    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try (SqlSession newSession = MybatisUtil.getSession()) {
            ManagerService freshService = new ManagerServiceImpl(newSession);
            Manager manager = (Manager) req.getSession().getAttribute("manager");
            // 获取今天的日期
            LocalDate today = LocalDate.now();
            String todayStr = today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            // 获取昨天的日期
            LocalDate yesterday = today.minusDays(1);
            String yesterdayStr = yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            // 获取7天前的日期
            LocalDate lastWeek = today.minusDays(7);
            String lastWeekStr = lastWeek.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            // 获取这周一的日期
            LocalDate thisMonday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            String thisMondayStr = thisMonday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            // 获取上周一的日期
            LocalDate lastMonday = thisMonday.minusWeeks(1);
            String lastMondayStr = lastMonday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            // 获取本月1号的日期
            LocalDate firstDayOfMonth = today.withDayOfMonth(1);
            String firstDayOfMonthStr = firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            // 获取上个月的日期
            LocalDate lastMonth = today.minusMonths(1);
            String lastMonthStr = lastMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            // 获取上个月1号的日期
            LocalDate firstDayOfLastMonth = lastMonth.withDayOfMonth(1);
            String firstDayOfLastMonthStr = firstDayOfLastMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            int todayOrderNum = freshService.getOrderCountByDate(todayStr);
            int yesterdayOrderNum = freshService.getOrderCountByDate(yesterdayStr);

            double money1 = freshService.getPaidOrderMoneyByDate(firstDayOfMonthStr, todayStr);
            double money2 = freshService.getPaidOrderMoneyByDate(firstDayOfLastMonthStr, lastMonthStr);

            int refundOrderCount1 = freshService.getRefundOrderNumByDate(thisMondayStr, todayStr);
            int refundOrderCount2 = freshService.getRefundOrderNumByDate(lastMondayStr, lastWeekStr);

            Context context = new Context();
            context.setVariable("managername", manager.getM_name());
            context.setVariable("todayOrderNum", todayOrderNum);
            if (yesterdayOrderNum == 0) {
                if (todayOrderNum == 0) context.setVariable("orderPercentSign", "no");
                else context.setVariable("orderPercentSign", "0");
            } else {
                double orderPercent = (double) (todayOrderNum - yesterdayOrderNum) / yesterdayOrderNum * 100;
                if (orderPercent < 0) {
                    orderPercent = -orderPercent;
                    context.setVariable("orderPercentSign", "negative");
                    context.setVariable("orderPercent", orderPercent);
                } else {
                    context.setVariable("orderPercentSign", "positive");
                    context.setVariable("orderPercent", orderPercent);
                }
            }
            context.setVariable("cancelledAndRefundOrderNum", freshService.getCancelledAndRefundOrderNum());
            context.setVariable("income", money1);
            if (money2 == 0) {
                if (money1 == 0) context.setVariable("incomePercentSign", "no");
                else context.setVariable("incomePercentSign", "0");
            } else {
                double moneyPercent = (money1 - money2) / money2 * 100;
                if (moneyPercent < 0) {
                    moneyPercent = -moneyPercent;
                    context.setVariable("incomePercentSign", "negative");
                    context.setVariable("incomePercent", moneyPercent + "%");
                } else {
                    context.setVariable("incomePercentSign", "positive");
                    context.setVariable("incomePercent", "+" + moneyPercent + "%");
                }
            }
            context.setVariable("refundOrderCounts", freshService.getRefundOrderCount());
            context.setVariable("refundOrderCount1", refundOrderCount1);
            if (refundOrderCount2 == 0) {
                if (refundOrderCount1 == 0) context.setVariable("refundPercentSign", "no");
                else context.setVariable("refundPercentSign", "0");
            } else {
                double refundPercent = (double) (refundOrderCount1 - refundOrderCount2) / refundOrderCount2 * 100;
                if (refundPercent < 0) {
                    refundPercent = -refundPercent;
                    context.setVariable("refundPercentSign", "negative");
                    context.setVariable("refundPercent", refundPercent + "%");
                } else {
                    context.setVariable("refundPercentSign", "positive");
                    context.setVariable("refundPercent", "+" + refundPercent + "%");
                }
            }
            if (req.getSession().getAttribute("order_operation_failure") != null) {
                context.setVariable("order_operation_failure", true);
                req.getSession().removeAttribute("order_operation_failure");
            }
            context.setVariable("allOrderCounts", freshService.getOrderNum());
            context.setVariable("unpaidOrderCounts", freshService.getUnpaidOrderNum());
            context.setVariable("paidOrderCounts", freshService.getPaidOrderNum());
            context.setVariable("cancelledOrderCounts", freshService.getCancelledOrderNum());
            context.setVariable("completedOrderCounts", freshService.getCompletedOrderNum());
            context.setVariable("orders", freshService.getOrderList());
            ThymeleafUtil.process("manager_order.html", context, resp.getWriter());
        }
    }
}
